
#include "../inc/XMLGenerator.h"


	XMLGenerator::XMLGenerator(){

	}

	void XMLGenerator::generate(char* outputFile, PageHistory &history,KeyWordIndex &index){

		file.open(outputFile);

		LinkedList<string> &words= *(index.getWords());
		addFirstPage(history.getBasePage());
		LinkedList<Page> &historyList= *(history.toLinkedList());

		file << "\t<pages>" << endl;
		for (int i=0;i<historyList.GetSize();i++){
			addPage(historyList.Get(i));		//Add all pages
		}
		file << "\t</pages>" << endl;

		file << "\t<index>" << endl;
		for (int i=0; i<words.GetSize();i++)
			addOccurrenceSet(words.Get(i),index.getSet(*(words.Get(i))));	//add all entries in the index
		file << "\t</index>" << endl;

		close();

		delete &historyList;
		delete &words;
	}

	void XMLGenerator::addFirstPage(Page* site){
		file << "<website>" << endl;
		file << "\t<start-url>" << site << "</start-url>" << endl;

	}
	void XMLGenerator::addPage(Page* site){
		file << "\t\t<page>" << endl;
		file << "\t\t\t<url>" << site << "</url>" << endl;
		file << "\t\t\t<description>" << site->getDescription() << "</description>" << endl;
		file << "\t\t</page>" << endl;
	}
	void XMLGenerator::addOccurrenceSet(string *key,OccurrenceSet* set){
		file<< "\t\t<word>"	<<endl;
		file<< "\t\t\t<value>" << *key << "</value>" << endl;
		LinkedList<Occurrence> &list= *(set->toLinkedList());
		for(int i=0; i< list.GetSize();i++){
			addOccurrence(list.Get(i));
		}
		file << "\t\t</word>" << endl;
		delete &list;
	}
	void XMLGenerator::addOccurrence(Occurrence* cur){
		file << "\t\t\t<occurrence>" << endl;
		file << "\t\t\t\t<url>" << cur->getSite() << "</url>" <<endl;
		file << "\t\t\t\t<count>" << cur->getCount() << "</count>" <<endl;
		file << "\t\t\t</occurrence>" << endl;
	}

	void XMLGenerator::close(){
		file << "</website>" << endl;
		file.close();
	}

